package redis

import (
	"fmt"
	"time"

	"gitee.com/krio/ginc/example/core/lib/conf"
	"gitee.com/krio/ginc/example/util/cmdprint"
	"github.com/gomodule/redigo/redis"
)

var redisPool *redis.Pool

// InitRedis 注册Redis
func InitRedis() *redis.Pool {
	cRedis := conf.C.Redis
	return getRedisPool(cRedis.Host, cRedis.Port, cRedis.Password, cRedis.MaxIdle, cRedis.DB)
}

// getRedisPool redis连接池
func getRedisPool(host string, port int, password string, maxIdle, db int) *redis.Pool {
	redisPool = &redis.Pool{
		MaxIdle: maxIdle, // 空闲数
		Dial: func() (redis.Conn, error) {
			c, err := redis.Dial("tcp", fmt.Sprintf("%s:%d", host, port), redis.DialPassword(password))
			if err != nil {
				return nil, err
			}
			if _, err = c.Do("SELECT", db); err != nil {
				return nil, err
			}
			return c, err
		},
		TestOnBorrow: func(c redis.Conn, t time.Time) error {
			if time.Since(t) > time.Minute {
				_, err := c.Do("PING")
				return err
			}
			return nil
		},
	}
	conn := redisPool.Get()
	defer conn.Close()

	if conn.Err() != nil {
		cmdprint.CmdFatal("配置解析失败: %+v", conn.Err())
	}

	if _, err := conn.Do("PING"); err != nil {
		cmdprint.CmdFatal("ping Redis失败: %+v", err)
	}

	cmdprint.CmdSuccess(fmt.Sprintf("redis: %s:%d/%d", host, port, db))
	return redisPool
}

// GetRedisPool return redis pool
func GetRedisPool() *redis.Pool {
	return redisPool
}
